package com.i2bt.app.files;

import com.i2bt.common.AndroidRestContract;
import com.i2bt.common.Contract;
import com.i2bt.common.UserConfig;

import com.i2bt.R;
import com.i2bt.adapter.FilesListAdapter;
import com.i2bt.app.BaseFragment;
import com.i2bt.app.files.model.FilesJsonHandle;
import com.i2bt.app.files.model.FilesTransmissionManager;
import com.i2bt.app.main.MainActivity;
import com.i2bt.bean.FileBean;
import com.i2bt.bean.FileInfoBean;
import com.i2bt.util.AlertDialogHelp;
import com.i2bt.util.DpAndPxConvertUtil;
import com.i2bt.util.VisibilityUtil;
import com.i2bt.view.XListView;
import com.i2bt.view.XListView.IXListViewListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 
 * Title : 我的目录碎片类
 * 
 * Description : 放在主界面中的碎片类, 这里面是对我的目录的显示和操作.
 * 
 * CreatedTime : 2014-8-11
 * 
 * @author wuliao & kakaxi & yi
 * 
 * @version 1.0
 * 
 */

public class FilesFragment extends BaseFragment implements
		OnItemLongClickListener {

	private XListView filesListView; // 我的目录列表
	
	private FilesListAdapter filesListAdapter; // 资源列表的适配器

	private LinearLayout filesTabbar; // 底部的按钮栏
	
	private PopupWindow filesTabbarMorePopup; // 更多弹出式菜单

	private List<FileInfoBean> filesList; // 存放文件信息的链表

//	private Map<String, String> homeboxMap; // 存放homebox的key为id, value为name

	private FilesJsonHandle filesJsonHandle; // 资源json处理器

	private List<Integer> filesCheckedList; // 资源勾选列表
	
	private int markPosition; // 位置标记
	
	public int currentPathAt = 0; // 当前目录的位置, 根目录为第一层

	private final static int UPMOVE_DURATION = 500; // 底部框上移的速度

	private final static String SP = "\\"; // 资源分隔符

	private boolean isBack = false; // 是否后退标志

	private RadioButton filesTabbarMore; // 更多按钮

	private LinearLayout filesTabbarRename; // 重命名布局
	
	private boolean isOneDownload; // 是否单文件下载

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if (filesJsonHandle == null) {
			filesJsonHandle = new FilesJsonHandle(this);
		}
		getFilesRequest();
		
	}
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		if (this.isVisible()) {
			if (isVisibleToUser) {

			}
		}
	}

	/*
	 * 获取目录列表
	 */
	public void getFilesRequest() {
		
		String pathTemp = UserConfig.currentFilesPath;
		if (isBack) {
			int index = UserConfig.currentFilesPath.lastIndexOf("\\");
			if (index == -1) {
				pathTemp = "";
			} else {
				pathTemp = UserConfig.currentFilesPath
						.substring(0, index);
			}
		}
		else {
			// -1为刷新操作
			if (filesList != null && filesList.size() != 0 && markPosition != -1) {
				
				String fileName = filesList.get(markPosition).getFileName();
				
				if (UserConfig.currentFilesPath.equals("")) {
					pathTemp = UserConfig.currentFilesPath + fileName;
				} else {
					pathTemp = UserConfig.currentFilesPath + SP + fileName;
				}
				
			}
		}
		
		// 打包获取文件的bean
		FileBean fileBean = new FileBean();
		fileBean.setAct(AndroidRestContract.GET_FILES);
		fileBean.setParentFolder(pathTemp);
		filesJsonHandle.postTo(AndroidRestContract.REST_FILES, fileBean);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_files, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
//		makeData();
		initView();
		logic();
		
//		FilesTransmissionManager.getInstance().addDownloadTask(activity, "127.0.0.1", 8821,
//				new FileInfoBean[] {new FileInfoBean("aa", 1000, true)});
//		String[] filePathList = new String[1];
//		filePathList[0] = Environment.getExternalStorageState() + SP + "com.aou.bubble_haibao.jpg";
//		new FilesUploadClient(activity, "192.168.23.1", 8821, filePathList).start();
	}
	
	private void makeData() {
		filesList = new ArrayList<FileInfoBean>();
		filesList.add(new FileInfoBean("hehe", 50000, true));
		filesList.add(new FileInfoBean("haha", 0, false));
		filesList.add(new FileInfoBean("E:", 0, false));
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void initView() {
		// 设置适配器,传入了资源信息类链表
		filesListAdapter = new FilesListAdapter(this, filesList);

		// 获取资源列表视图
		filesListView = (XListView) activity.findViewById(R.id.files_list);
		filesListView.setPullLoadEnable(false);
		filesListView.setOnItemClickListener(this);
		filesListView.setOnItemLongClickListener(this);
		// 处理连续滚动后列表项点击失效
		filesListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					filesListView.invalidateViews();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

			}
		});
		filesListView.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				markPosition = -1;
				getFilesRequest();
			}

			@Override
			public void onLoadMore() {
			}
		});
		filesListView.setAdapter(filesListAdapter);

		//初始化底部栏
		filesTabbar = (LinearLayout) activity.findViewById(R.id.files_tabbar);
		filesTabbar.setOnClickListener(this);

		//初始化4个底部按钮
		RadioButton filesTabbarDelete = (RadioButton) activity
				.findViewById(R.id.files_tabbar_delete);
		filesTabbarDelete.setOnClickListener(this);

		RadioButton filesTabbarDownload = (RadioButton) activity
				.findViewById(R.id.files_tabbar_download);
		filesTabbarDownload.setOnClickListener(this);

		RadioButton filesTabbarShared = (RadioButton) activity
				.findViewById(R.id.files_tabbar_share);
		filesTabbarShared.setOnClickListener(this);
		
		filesTabbarMore = (RadioButton) activity
				.findViewById(R.id.files_tabbar_more);
		filesTabbarMore.setOnClickListener(this);
		
		//初始化弹出式菜单
		View morePopupView = activity.getLayoutInflater().
				inflate(R.layout.item_files_tabbar_more_popup, null);
		filesTabbarMorePopup = new PopupWindow(morePopupView,
				DpAndPxConvertUtil.DpToPx(activity, 96), 
				DpAndPxConvertUtil.DpToPx(activity, 96));
		filesTabbarMorePopup.setFocusable(true);
		filesTabbarMorePopup.setBackgroundDrawable(new BitmapDrawable());
		
		//初始化重命名
		filesTabbarRename = (LinearLayout) morePopupView.findViewById(
				R.id.files_tabbar_rename);
		filesTabbarRename.setOnClickListener(this);
		
		//初始化移动到
		LinearLayout filesTabbarMove = (LinearLayout) morePopupView.findViewById(
				R.id.files_tabbar_move);
		filesTabbarMove.setOnClickListener(this);
	}

	@Override
	protected void logic() {
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position,
			long id) {
		position--;
		if (filesListAdapter.getChecked()) {
			// 当为勾选状态的时候每次点击都会设置该勾选按钮的状态,并且检查已勾选的数量
			boolean isChecked = filesListAdapter.getCheckedItem(position);
			setChecked(position, !isChecked);
		} else {

			// 当没勾选状态时, 点击就会对文件进行下载或者进入文件夹
			FileInfoBean fileBean = filesList.get(position);
			if (fileBean.isFile()) {
				
				AlertDialogHelp.showConfirmDialog(activity, "下载文件", "确定下载此文件?",
						new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 下载单个文件
						downloadOneFileRequest();
					}
				}, null);
				
			} else {
				// 获取下一层目录
				markPosition = position;
				isBack = false;
				getFilesRequest();
			}

		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> adapter, View view,
			int position, long id) {
		// xlistview的一个位置bug
		position--;
		if (filesListAdapter.getChecked()) {
			
		} else {
			if (currentPathAt > 2) {
				filesListAdapter.setCheckedItem(position, true);
				changeType(true);
			}
		}

		return true;
	}

	/**
	 * 已选择数量监控
	 */
	public void checkNumberCheck() {

		boolean hasCheck = false;
		//获取已选择的数量
		int n = filesListAdapter.getCheckedCount();
		//如果选择了多项, 把重命名布局设置为不可点击, 只能选择一项
//		if (n > 1) {
//			filesTabbarRename.setClickable(false);
//		}
//		else {
//			filesTabbarRename.setClickable(true);
//		}
		// 判断是否有选起码一项, 有的话就继续保持选定状态, 没有就会自动还原回普通模式
		if (n > 0) {
			hasCheck = true;
		}
		if (hasCheck) {
			// 实时设置actionbar的文本显示为选择的列表项数量
			activity.setActionBarTitle("已选定" + n + "个");
			// 当选择了当前目录所有项时就会把全选键变成取消, 否则相反
			if (filesList.size() == filesListAdapter.getCheckedCount()) {
				showAllCheckedMenuItem(false);
			} else {
				showAllCheckedMenuItem(true);
			}
		} else {
			//还原回普通模式, 显示app名
			activity.setActionBarTitle(Contract.TITLE_APP_NAME);
			changeType(hasCheck);
		}

	}

	/**
	 * 切换我的目录模式,  是为选择模式, 否为普通模式
	 * @param isChecked
	 */
	public void changeType(boolean isChecked) {
		// 设置目录列表的选择模式标志
		filesListAdapter.setChecked(isChecked);
		// 当切换回普通模式时会自动把所选的数量清空, 以防下次选择模式会出现上次选的
		if (!isChecked) {
			filesListAdapter.setAllChecked(isChecked);
		}
		// 设置可否点击选择按钮, 当选择模式时点列表项才会打钩, 而普通模式可点图标做切换并打钩
		filesListAdapter.setClickable(!isChecked);
		// 刷新
		filesListAdapter.notifyDataSetChanged();

		// 设置是否显示后退按钮
		activity.setShowBackBtn(isChecked);
		//显示或取消全选菜单
		showFilesCheckMenuGroup(isChecked);

		//设置是否显示或隐藏底部栏
		setBottomBar(isChecked);
		
		// 当变成选择模式是 重命名按钮就会可点击, 因为有时候可能选多个文件时就转回普通模式
//		filesTabbarRename.setClickable(isChecked);
	}

	/**
	 * 切换底部栏
	 * @param isShow
	 */
	public void setBottomBar(boolean isShow) {

		VisibilityUtil.setVisibilityUI(filesTabbar, isShow);
		if (isShow) {

			TranslateAnimation moveAnim = new TranslateAnimation(
					Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
					0f, Animation.RELATIVE_TO_SELF, 1.0f,
					Animation.RELATIVE_TO_SELF, 0.0f);
			moveAnim.setDuration(UPMOVE_DURATION);

			filesTabbar.startAnimation(moveAnim);
		}

	}

	/**
	 * 设置某个目录的选择状态, 并检测选择的数量
	 * @param position
	 * @param isChecked
	 */
	public void setChecked(int position, boolean isChecked) {
		filesListAdapter.setCheckedItem(position, isChecked);
		checkNumberCheck();
		filesListAdapter.notifyDataSetChanged();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		//更多
		case R.id.files_tabbar_more : {
			showMorePopup();
			break;
		}

		//删除
		case R.id.files_tabbar_delete : {
			deleteFilesRequest();
			break;
		}

		//下载
		case R.id.files_tabbar_download : {
			downloadFilesRequest();
			break;
		}
			
		//分享
		case R.id.files_tabbar_share : {
			toShareFiles();
			break;
		}
			
		//重命名
		case R.id.files_tabbar_rename : {
			renameFilesRequest();
			break;
		}
			
		// 移动到
		case R.id.files_tabbar_move :  {
			toMoveFiles();
			break;
		}
		
		}
		
	}
	
	/**
	 * 展示出弹出式菜单
	 */
	private void showMorePopup() {
		if (filesTabbarMorePopup.isShowing()) {
			filesTabbarMorePopup.dismiss();
		}
		else {
			filesTabbarMorePopup.showAsDropDown(filesTabbarMore, 
					DpAndPxConvertUtil.DpToPx(activity, -20),
					DpAndPxConvertUtil.DpToPx(activity, 1));
		}
	}

	/**
	 * 当向云端获取目录后就会调用这个方法, 让列表视图显示出当前目录下的资源
	 * 
	 * @param filesList
	 *            资源链表
	 */ 
	public void getFilesResponse(List<FileInfoBean> filesList) {
		if (isBack) {
			int index = UserConfig.currentFilesPath.lastIndexOf("\\");
			if (index == -1) {
				UserConfig.currentFilesPath = "";
			} else {
				UserConfig.currentFilesPath = UserConfig.currentFilesPath
						.substring(0, index);
			}
		}
		else {
			if (this.filesList != null && this.filesList.size() != 0 && markPosition != -1) {
				String fileName = this.filesList.get(markPosition).getFileName();
				if (UserConfig.currentFilesPath.equals("")) {
					UserConfig.currentFilesPath += fileName;
				} else {
					UserConfig.currentFilesPath += SP + fileName;
				}
			}
		}
		
		// 把数据放入, 并刷新数据
		this.filesList = filesList;
		filesListAdapter.setData(filesList);
		filesListAdapter.notifyDataSetInvalidated();
		
		if (isBack) {
			// 成功退回时, 位置减, 当退到首目录时就把后退键隐藏
			if (currentPathAt != 0) {
				currentPathAt--;
			}
		} else {
			// 当前位置加1, 如果进入目录里面时就会显示后退键
			if (markPosition != -1) {
				currentPathAt++;
			}
		}
		if (currentPathAt > 1) {
			((MainActivity) activity).setShowBackBtn(true);
		} else {
			((MainActivity) activity).setShowBackBtn(false);
		}
		filesListView.stopRefresh();
	}
	
	/**
	 * 请求删除资源
	 */
	private void deleteFilesRequest() {
		AlertDialogHelp.showConfirmDialog(activity, "删除文件", "确认删除这些文件?",
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 获取勾选的列表项列表位置
						filesCheckedList = filesListAdapter.getCheckedList();

						String[] removeFilePaths = new String[filesCheckedList
								.size()];
						int i = 0;
						for (Integer position : filesCheckedList) {
							String fileName = filesList.get(position)
									.getFileName();
							String path = UserConfig.currentFilesPath + SP
									+ fileName;
							removeFilePaths[i] = path;
							try {
								removeFilePaths[i] = URLEncoder.encode(removeFilePaths[i], "utf-8");
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
							i++;
						}

						FileBean fileBean = new FileBean();
						fileBean.setAct(AndroidRestContract.DELETE_MULT_FILES);
						fileBean.setRemoveFilePaths(removeFilePaths);

						filesJsonHandle.postTo(AndroidRestContract.REST_FILES,
								fileBean);
					}
				}, null);
	}

	/**
	 * 响应删除资源
	 */
	public void deleteFilesResponse() {

		// 删除时的差值, 当删除项的时候下面的项会上移
		int difference = 0;
		for (int i = 0; i < filesCheckedList.size(); i++) {
			filesList.remove(filesCheckedList.get(i) - difference);
			difference++;
		}

		filesListAdapter.notifyDataSetChanged();
		// 删除后关闭勾选模式
		changeType(false);

		toastHandler("删除成功!");

	}

	/**
	 * 请求重名命资源
	 */
	private void renameFilesRequest() {

		if (filesListAdapter.getCheckedCount() == 1) {

			filesCheckedList = filesListAdapter.getCheckedList();
			final String previousName = filesList.get(filesCheckedList.get(0))
					.getFileName();

			AlertDialogHelp.showEditDialog(activity, "重命名", "", previousName,
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							String previousPath = UserConfig.currentFilesPath
									+ SP + previousName;

							EditText renameEdit = (EditText) AlertDialogHelp
									.getCommonView();
							String newPath = UserConfig.currentFilesPath + SP
									+ renameEdit.getEditableText().toString();

							FileBean fileBean = new FileBean();
							fileBean.setAct(AndroidRestContract.RENAME_FILES);
							fileBean.setPreviousPath(previousPath);
							fileBean.setNewPath(newPath);

							filesJsonHandle.postTo(
									AndroidRestContract.REST_FILES, fileBean);
						}

					}, null);
		} else {
			toastHandler("不可同时更改多个资源名称");
		}

	}

	/**
	 * 响应重命名资源
	 */
	public void renameFilesResponse() {
		EditText renameEdit = (EditText) AlertDialogHelp.getCommonView();
		filesList.get(filesCheckedList.get(0)).setFileName(
				renameEdit.getEditableText().toString());
		toastHandler("修改成功!");
	}

	/**
	 * 假下载
	 */
	public void downloadFiles() {

		final ProgressDialog pro = new ProgressDialog(activity);
		pro.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pro.setTitle("正在下载文件");
		pro.setIndeterminate(false);
		pro.setCancelable(true);

		pro.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				toastHandler("进入后台下载..");
			}
		});

		pro.show();
		pro.incrementProgressBy(10);

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (pro.getProgress() < 100) {
					pro.incrementProgressBy((int) (Math.random() * 15));
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				toastHandler("下载成功!");
				pro.dismiss();
			}
		}).start();
	}
	
	private void downloadOneFileRequest() {
		FileInfoBean[] fileInfoBean1 = new FileInfoBean[1];
		fileInfoBean1[0]	=  new FileInfoBean("aa.txt", 100, true);
		FilesTransmissionManager.getInstance().addDownloadTask(activity, "192.168.23.1", 8821, fileInfoBean1);
		
		// 取出将要下载
		FileInfoBean fileInfoBean = filesList.get(markPosition);
		// 将要下载的文件名
		String fileName = fileInfoBean.getFileName();
		String[] downloadFilePath = new String[1];
		// 与父路径构成下载路径
		downloadFilePath[0] = UserConfig.currentFilesPath + SP + fileName;

		// 打包下载路径
		FileBean fileBean = new FileBean();
		fileBean.setAct(AndroidRestContract.DOWNLOAD_FILES);
		fileBean.setDownloadFiles(downloadFilePath);
		
		filesJsonHandle.postTo(AndroidRestContract.REST_FILES, fileBean);
		
		isOneDownload = true;
	}
	
	/**
	 * 下载请求
	 */
	private void downloadFilesRequest() {
		
		boolean canDownload = true;
		
		filesCheckedList = filesListAdapter.getCheckedList();
		String[] downloadFilePath = new String[filesCheckedList.size()];
		for (int i = 0; i < filesCheckedList.size(); i++) {
			if (!filesList.get(i).isFile()) {
				canDownload = false;
				break;
			}
			
			System.out.println(filesCheckedList.size());
			
			downloadFilePath[i] = UserConfig.currentFilesPath + SP
					+ filesList.get(filesCheckedList.get(i)).getFileName();
			try {
				downloadFilePath[i] = URLEncoder.encode(downloadFilePath[i], "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		if (currentPathAt == 1) {
			toastHandler("不可下载homebox");
			return;
		}
		
		if (currentPathAt == 2) {
			toastHandler("暂不可下载硬盘");
			return;
		}
		
		if (!canDownload) {
			toastHandler("暂不可下载文件夹");
			return;
		}
		
		FileBean fileBean = new FileBean();
		fileBean.setAct(AndroidRestContract.DOWNLOAD_FILES);
		fileBean.setDownloadFiles(downloadFilePath);
		filesJsonHandle.postTo(AndroidRestContract.REST_FILES, fileBean);
	}
	
	/**
	 * 下载文件响应
	 * @param ip ip地址
	 * @param port 端口号
	 */
	public void downloadFilesResponse(String ip, int port) {
		
		FileInfoBean[] fileInfoBeans = null;
		// 单文件下载
		if (isOneDownload) {
			// 把文件信息取出放到信息数组中
			fileInfoBeans = new FileInfoBean[1];
			fileInfoBeans[0] = filesList.get(markPosition);
		}
		else {
			// 获取选中的多个路径进行下载
			fileInfoBeans = new FileInfoBean[filesCheckedList.size()];
			
			for (int i = 0; i < filesCheckedList.size(); i++) {
				fileInfoBeans[i] = filesList.get(filesCheckedList.get(i));
			}
		}
		
		// 获取传输管理器, 新增加载任务
		FilesTransmissionManager manager = FilesTransmissionManager.getInstance();
		manager.addDownloadTask(activity, ip, port, fileInfoBeans);
		
	}
 	
	/**
	 * 跳转移动文件
	 */
	private void toMoveFiles() {
		
		// 获取位置选中列表
		filesCheckedList = filesListAdapter.getCheckedList();
		String[] movePreviousPathsList = new String[filesCheckedList.size()];
		// 把选中的文件路径放入列表中
		for (int i = 0; i < movePreviousPathsList.length; i++) {
			int position = filesCheckedList.get(i);
			FileInfoBean fileInfoBean = filesList.get(position);
			// 当前路径加上文件名构造成旧路径
			movePreviousPathsList[i] = UserConfig.currentFilesPath + 
					fileInfoBean.getFileName();
		}
		
		// 传递参数, 打开文件移动活动类
		Bundle bundle = new Bundle();
		bundle.putStringArray(Contract.BUNDLE_FILES_MOVE_PREPATH_LIST, movePreviousPathsList);
		goActivityAndResult(FilesMoveActivity.class, bundle, 
				Contract.FILES_AND_MOVE_REQUESTCODE);
		
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == Activity.RESULT_OK) {
			
			switch (requestCode) {
			
			case Contract.FILES_AND_MOVE_REQUESTCODE: {
				// 文件移动确认后返回主界面时刷新我的目录列表
				markPosition = -1;
				getFilesRequest();
				break;
			}
				
			}
			
		}
	}

	public void toShareFiles() {
		
		Bundle bundle = new Bundle();
		bundle.putParcelableArray(Contract.BUNDLE_FILES_SHARED_PATH_LIST,
				getCheckedSharedPath());
		goActivity(FilesSharedActivity.class, bundle);
	}
	
	/**
	 * 获取分享路径
	 * @return
	 */
	private FileInfoBean[] getCheckedSharedPath() {
		// 选中的文件列表位置
		List<Integer> filesCheckedList = filesListAdapter.getCheckedList();
		// 分享文件的路径数组
		FileInfoBean[] sharedPathList = new FileInfoBean[filesCheckedList.size()];
		for (int i = 0; i < sharedPathList.length; i++) {
			sharedPathList[i] = filesList.get(filesCheckedList.get(i));
		}
		return sharedPathList;
	}

	/**
	 * 请求创建文件夹
	 */
	public void createFilesRequest() {
		
		// 创建文件夹失败判定
		if (currentPathAt == 0) {
			toastHandler("无法新建文件夹");
			return;
		}
		else if (currentPathAt == 1) {
			toastHandler("无法在homebox目录新建文件夹");
			return;
		}
		else if (currentPathAt == 2) {
			toastHandler("无法在硬盘目录新建文件夹");
			return;
		}
			
		
		AlertDialogHelp.showEditDialog(activity, "新建文件夹", "新建文件夹", "",
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						EditText createEdit = (EditText) AlertDialogHelp
								.getCommonView();
						String folderName = createEdit.getText().toString();
						System.out.println(folderName);

						FileBean fileBean = new FileBean();
						fileBean.setAct(AndroidRestContract.CREATE_FILES);
						fileBean.setParentPath(UserConfig.currentFilesPath);
						fileBean.setFolderName(handleRepeatFilesName(folderName));

						filesJsonHandle.postTo(AndroidRestContract.REST_FILES,
								fileBean);
					}
				}, null);
	}
	
	/**
	 * 处理创建文件夹时目录下与其他文件同名
	 * @param newFileName 新文件夹名
	 * @return 没同名的文件夹名
	 */
	public String handleRepeatFilesName(String newFileName) {
		int count = 0;
		String finalFileName = newFileName;
		for (int i = 0; i < filesList.size(); i++) {
			FileInfoBean fileInfoBean = filesList.get(i);
			String otherFileName = fileInfoBean.getFileName();
			// 如果有同名文件, 就会计数加1, 重新生成一个带括号的文件夹名, 再重新循环直到没有同名
			if (newFileName.equals(otherFileName)) {
				count++;
				finalFileName = newFileName + "(" + count + ")";
				i = 0;
			}
		}
		return finalFileName;
	}

	/**
	 * 响应创建文件夹
	 */
	public void createFilesResponse() {
		EditText createEdit = (EditText) AlertDialogHelp.getCommonView();
		String newFolderName = createEdit.getEditableText().toString();
		filesList.add(new FileInfoBean(newFolderName, 0, false));
	}

	public void setHomeboxMap(Map<String, String> homeboxMap) {
//		this.homeboxMap = homeboxMap;
	}

	@Override
	public void backHomeOperate() {

		if (filesListAdapter.getChecked()) {
			changeType(false);
			checkNumberCheck();
		} else {
			onKeyBack();
		}
	}

	@Override
	public boolean onKeyBack() {
		
		if (filesListAdapter.getChecked()) {
			//如果弹出式菜单弹出就先关闭
			if (filesTabbarMorePopup.isShowing()) {
				filesTabbarMorePopup.dismiss();
				return true;
			}
			//进入目录选择状态的话就先退出选择状态
			changeType(false);
			return true;
		}
		else {
			if (currentPathAt > 1) {
				isBack = true;
				getFilesRequest();
				return true;
			} else {
				return false;
			}
		}
		
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		menu.clear();
		inflater.inflate(R.menu.files_menu, menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		
		case R.id.action_create : 
			createFilesRequest();
			break;
			
		case R.id.action_upload : 
			goActivity(FilesUploadActivity.class);
			break;
			
		case R.id.files_all_checked :
			getFilesListAdapter()
			.setAllChecked(true);
			showAllCheckedMenuItem(false);
			break;
			
		case R.id.files_all_cancel :
			changeType(false);
			checkNumberCheck();
			showFilesCheckMenuGroup(false);
			break;
		
		}
		
		return true;
	}
	
	public void showFilesCheckMenuGroup(boolean isShow) {
		menu.setGroupVisible(R.id.group_files_checked, isShow);
		menu.setGroupVisible(R.id.group_main_action, !isShow);
		menu.setGroupVisible(R.id.group_files_action, !isShow);

		if (isShow) {
			showAllCheckedMenuItem(isShow);
		}
	}

	public void showAllCheckedMenuItem(boolean isShow) {
		menu.findItem(R.id.files_all_checked).setVisible(isShow);
		menu.findItem(R.id.files_all_cancel).setVisible(!isShow);
	}
	
	/**
	 * 获取资源列表适配器
	 * @return
	 */
	public FilesListAdapter getFilesListAdapter() {
		return filesListAdapter;
	}
	
	/**
	 * 获取当前目录位置
	 * @return
	 */
	public int getCurrentPathAt() {
		return currentPathAt;
	}
	
	/**
	 * 获取文件列表
	 */
	public XListView getListView() {
		return filesListView;
	}
	
}
